package com.hltx.controller.user;


import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.hltx.controller.base.BaseController;
import com.hltx.pojo.common.Page;
import com.hltx.pojo.smscode.SmsCodeValidate;
import com.hltx.pojo.user.CashUser;
import com.hltx.pojo.user.User;
import com.hltx.pojo.user.UserAccount;
import com.hltx.service.brokerage.impl.ConsumeBrokerageService;
import com.hltx.service.smscode.impl.SmsCodeValidateService;
import com.hltx.service.user.BonusManager;
import com.hltx.service.user.UserManager;
import com.hltx.service.user.UserPayManager;
import com.hltx.util.MessagesCode;
import com.hltx.util.ResultInfo;

@Controller
@RequestMapping("/user/myvip")
public class UserPayController extends BaseController {
	
	@Resource(name="userService")
	private UserManager userService;
	
	//提现业务层
	@Resource(name="userPayService")
	private UserPayManager userPayService;
	
	//奖金明细业务层
	@Resource(name="bonusService")
	private BonusManager bonusService;
	//验证码
	@Resource(name="smsCodeValidateService")
	private SmsCodeValidateService smsCodeValidateService;
	@Resource(name="consumeBrokerageService")
	private ConsumeBrokerageService brokerageService;


	/**
	 * session 域获取user对象
	 * 
	 */
	private static User getUser(HttpSession session){
		User user = (User) session.getAttribute("sessionUser");
		return user;
	}
	
	/**
	 * 提现页面
	 * @return
	 */
	@RequestMapping("/withdraw")
	public ModelAndView getUser(User user){
		
		ModelAndView  mv = new ModelAndView();
		user=userService.getUser(user);
		/*CashUser cu = new CashUser();
		cu.setUserId(user.getId());
		cu.setState("00");  //状态 00:正在处理   01:提现成功  02:提现失败
		BigDecimal appayIng =userPayService.getApplyIng(cu);  //获取的状态为0的提现的总额
		BigDecimal balance;
		if(appayIng != null){
			balance =user.getBalance().subtract(appayIng);  // 提现成功后所剩余额   
			user.setBalance(balance);
			cu.setState("01");  //提现成功设置状态问 01
		}*/
		mv.setViewName("user/rebate_apply");
		mv.addObject("user",user);
		return mv;
	}
	
	/**
	 * 提现
	 * @param request
	 * @param response
	 */
	@RequestMapping(value="/userApply" , method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public Map<String,Object> userApply(HttpServletRequest request,HttpServletResponse response,CashUser cashUser){
		this.logBefore(logger, "提现");
		HashMap<String,Object> map = new HashMap<String,Object>();
		//PrintWriter out = null;	
		if (validateCocde(request)) {
		try {
			 //格式化时间
			 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			 cashUser.setCreateTime(dateFormat.format(new Date())); 
			 cashUser.setUpdateTime(dateFormat.format(new Date()));
			 //状态
			 cashUser.setState("00");    
			 //添加到表中
			 cashUser.setUserId(cashUser.getId());
			 userPayService.insert(cashUser);
			 map.put("result", this.initResult(ResultInfo.SUCCESS, "ok", "提现成功"));
		
		}
		catch (Exception e) {
			e.printStackTrace();
			this.logError(logger, e.getMessage());
			map.put("result", this.initResult(ResultInfo.ERROR, "exception", "系统异常"));
			}
		}else{
			 map.put("result", this.initResult(ResultInfo.ERROR, "error", MessagesCode.VALIDATE_EORROR));
		}
		this.logAfter(logger);
		return map;
	}
	
	/**
	 * 跳转奖金明细页面
	 */
	
	@RequestMapping("/bonus")
	public ModelAndView bonus( User user){
		ModelAndView  mv = new ModelAndView();
		user=userService.getUser(user);
		Integer userId = user.getId();
		UserAccount userAccount = brokerageService.cgetAccount(userId);
		mv.setViewName("user/bonus");
		mv.addObject("user", user);
		mv.addObject("userAccount", userAccount);
		return mv;
	}



	/**
	 * 奖金数据  明细 
	 */
	
	@RequestMapping(value = "/getBonus", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public Map<String, Object> getBonus(Page p ,HttpServletRequest request , HttpSession session){
		this.logBefore(logger, "奖励明细");
		HashMap<String,Object> map = new HashMap<String,Object>();
		User user = getUser(session);
		
		p.getParams().put("id",user.getId());
		
		try {
			List<Map<String, Object>> bonusMap = bonusService.getBonus(p);
			// 用作回显数据
			map.put("bonusMap", bonusMap);
			map.put("result", this.initResult(ResultInfo.SUCCESS, "ok", "成功"));
		} catch (Exception e) {
			e.printStackTrace();
			this.logError(logger, e.getMessage());
			map.put("result", this.initResult(ResultInfo.ERROR, "exception", "系统异常"));
		}

		this.logAfter(logger);

		return map;
	}
	
	//验证码
	private boolean validateCocde(HttpServletRequest request) {
		String phone = request.getParameter("payeePhone");
		String code = request.getParameter("code");
		String types = request.getParameter("type");
		SmsCodeValidate sms = new SmsCodeValidate();
		sms.setPhone(phone);
		sms.setCode(code);
		sms.setTypes(types);
		try {
			SmsCodeValidate validate = smsCodeValidateService.getSmsCode(sms);
			if(validate != null){
				smsCodeValidateService.IntiSmsCode(sms);
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	
}
